
import 'dart:io';
import 'dart:async';
import 'dart:typed_data';
// import 'package:bj_car/widgets/my_app_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/shims/dart_ui_real.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:magic_car/res/colors.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/config.dart';

import 'package:orientation/orientation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:ui' as ui show ImageByteFormat, Image;

import 'package:provider/provider.dart';
import 'package:toast/toast.dart';

///
/// Description: 签名画板并截图
///
class BuchongDrawingBoardPage extends StatefulWidget {
  @override
  _DrawingBoardPageState createState() => _DrawingBoardPageState();
}

class _DrawingBoardPageState extends State<BuchongDrawingBoardPage> {
  /// 标记签名画板的Key，用于截图
  GlobalKey _globalKey;

  /// 已描绘的点
  List<Offset> _points = <Offset>[];

  /// 记录截图的本地保存路径
  String _imageLocalPath;

  File signFile;

  final Imgpicker = ImagePicker();
  PickedFile selectimg;
  TextEditingController buchongcontroller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    // Init
    _globalKey = GlobalKey();
  }

  @override
  void dispose() {
    super.dispose();
    // 强制竖屏
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown
    // ]);
    // OrientationPlugin.forceOrientation(DeviceOrientation.portraitUp);
  }

  //pickimg
  _pickimg(type) async {
    // File img;
    if (type == 1) {
      //相机
      // selectimg = Imgpicker.getImage(source: source)
      //selectimg = Imgpicker.getImage(source: ImageSource.camera);
      selectimg = await Imgpicker.getImage(source: ImageSource.camera);
    } else {
      // List imgs = await PhotoPicker.pickAsset();
      selectimg = await Imgpicker.getImage(source: ImageSource.gallery);
    }
    if (selectimg == null) return;
    setState(() {
      selectimg = selectimg;
      _points?.clear();
      _points = [];
      _imageLocalPath = null;
    });
  }

  //selectphoto
  _selectpic() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            child: Padding(
                padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                child: Container(
                  height: 80,
                  child: new Column(children: <Widget>[
                    new Container(
                        decoration: new BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    width: 1, color: Color(0xffe5e5e5)))),
                        height: 40,
                        child: new GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () async {
                              Navigator.pop(context);
                              _pickimg(1);
                            },
                            child: Center(
                                child: Text('相机',
                                    style: TextStyle(
                                        fontSize: 16, color: Colors.red))))),
                    new Container(
                        height: 40,
                        child: new GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () async {
                              Navigator.pop(context);
                              _pickimg(2);

                              // uploadImg(2);
                            },
                            child: Center(
                                child: Text('相册',
                                    style: TextStyle(fontSize: 16))))),
                  ]),
                )),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return
        // RotatedBox(quarterTurns: 1,child:
        Scaffold(
      resizeToAvoidBottomInset: false,
      // appBar: MyAppBar(title:"签名"),
      appBar: AppBar(
        titleSpacing: 0,
          elevation: 0, backgroundColor: Colors.white, title: Text('补充说明',style: TextStyle(fontSize: Config.title_size),)),
      body: Container(
        // margin: EdgeInsets.fromLTRB(16.0, 12.0, 16.0, 0.0),
        child: Column(
          children: <Widget>[
            Container(
                alignment: Alignment.topCenter,
                padding: EdgeInsets.only(left: 10, right: 10),
                child: TextFormField(
                  controller: buchongcontroller,
                  style: TextStyle(fontSize: 14),
                  decoration: InputDecoration(
                      hintText: "输入补充说明内容", border: InputBorder.none),
                )),
            Expanded(
                child: RepaintBoundary(
              key: _globalKey,
              child: Container(
                //  height: 180.0,
                //  width: 200,
                decoration: BoxDecoration(
                  color: Colours.base_page_color,
                  border: Border.all(color: Colors.grey, width: 0.5),
                ),
                //  child:

                // Text('签名')
                child: Stack(
                  children: [
                    selectimg != null
                        ? Container(
                            child: Center(
                                child: Image.file(
                            File(selectimg.path),
                            fit: BoxFit.contain,
                          )
                                // Image.file(
                                //     selectimg)
                                ))
                        : Container(height: 0),
                    GestureDetector(
                      onPanUpdate: (details) => _addPoint(details),
                      onPanEnd: (details) => _points.add(null),
                    ),
                    CustomPaint(
                      painter: BoardPainter(_points),
                    ),
                  ],
                ),
              ),
            )),

            Row(
              children: <Widget>[
                RaisedButton(
                  color: Colours.bj_green_g1,
                  onPressed: () async {
                    setState(() {
                      _points?.clear();
                      _points = [];
                      _imageLocalPath = null;
                    });
                  },
                  child: Text(
                    '重新标注',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                Expanded(child: Container()),
                RaisedButton(
                  color: Colours.bj_green_g1,
                  onPressed: () async {
                    _selectpic();
                    // setState(() {
                    //   _points?.clear();
                    //   _points = [];
                    //   _imageLocalPath = null;
                    // });
                  },
                  child: Text(
                    '选择图片',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                Expanded(child: Container()),
                RaisedButton(
                  color: Colours.bj_orange_o1,
                  onPressed: () async {
                    // File toFile = await _saveImageToFile();
                    // String toPath = await _capturePng(toFile);
                    // print('Signature Image Path: $toPath');
                    // setState(() {
                    //   _imageLocalPath = toPath;
                    //   signFile = toFile;
                    // });
                    // uploadsignpic();
                    _savepic();
                  },
                  child: Text(
                    '确认',
                    style: TextStyle(
                      fontSize: 14.0,
                      color: Colors.white,
                      fontWeight: FontWeight.normal,
                    ),
                  ),
                ),
              ],
            ),

            // Container(
            //   alignment: Alignment.centerLeft,
            //   margin: EdgeInsets.only(top: 4.0),
            //   child: Text('Image local path:'),
            // ),
            // Container(
            //   alignment: Alignment.centerLeft,
            //   margin: EdgeInsets.only(top: 4.0),
            //   child: Text(
            //     _imageLocalPath ?? '',
            //     style: TextStyle(color: Colors.blue),
            //   ),
            // ),
            // Container(
            //   alignment: Alignment.centerLeft,
            //   margin: EdgeInsets.only(top: 4.0),
            //   child: Text('Show Image: '),
            // ),
            // Container(
            //   height: 180.0,
            //   margin: EdgeInsets.only(top: 4.0),
            //   alignment: Alignment.center,
            //   decoration: BoxDecoration(
            //     border: Border.all(color: Colors.grey, width: 0.5),
            //   ),
            //   child: Image.file(File(_imageLocalPath ?? '')),
            // )
          ],
        ),
      ),
      // )
    );
  }

  //上传签名图片
  uploadsignpic() async {
    if (selectimg == null) {
      Toast.show("请上传图片", context);
      return;
    }
    //  File _files = await FlutterNativeImage.compressImage(_imageLocalPath);

    Map<String, String> map = new Map();

    HttpHelper.upLoadSignImage(_imageLocalPath, (data) {
      //loadpage.close();
      print(data);
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        if (buchongcontroller.text.isEmpty) {
          Toast.show("请输入说明文字", context);
          return;
        }
        var param = {
          'img': data["url"],
          'remark': buchongcontroller.text.isEmpty ? "" : buchongcontroller.text
        };
        Navigator.of(context).pop(param);
      }
    }, params: map);
  }

  /// 添加点，注意不要超过Widget范围
  _addPoint(DragUpdateDetails details) {
    RenderBox referenceBox = _globalKey.currentContext.findRenderObject();
    Offset localPosition = referenceBox.globalToLocal(details.globalPosition);
    double maxW = referenceBox.size.width;
    double maxH = referenceBox.size.height;
    // 校验范围
    if (localPosition.dx <= 0 || localPosition.dy <= 0) return;
    if (localPosition.dx > maxW || localPosition.dy > maxH) return;
    setState(() {
      _points = List.from(_points)..add(localPosition);
    });
  }

  /// 选取保存文件的路径
  Future<File> _saveImageToFile() async {
    Directory tempDir = await getTemporaryDirectory();
    int curT = DateTime.now().millisecondsSinceEpoch;
    String toFilePath = '${tempDir.path}/$curT.png';
    File toFile = File(toFilePath);
    bool exists = await toFile.exists();
    if (!exists) {
      await toFile.create(recursive: true);
    }
    return toFile;
  }

  //保存图片
  _savepic() async {
    BuildContext buildContext = _globalKey.currentContext;
    if (null != buildContext) {
      RenderRepaintBoundary boundary = buildContext.findRenderObject();
      var dpr = window.devicePixelRatio;
      ui.Image image = await boundary.toImage(pixelRatio: dpr);
        // ByteData byteData =
        //   await image.toByteData(format: ui.ImageByteFormat.rawRgba);
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      if (Platform.isAndroid) {
        if (await Permission.storage.request().isGranted) {
          print('11111');
          if (Platform.isAndroid) {
            final result = await ImageGallerySaver.saveImage(
                byteData.buffer.asUint8List());
            //  final result = await ImageGallerySaver.saveImage(
            //     byteData.buffer.asByteData());
            String res1 = result['filePath'];
            print(result);
            String path = res1.replaceAll("file://", '');
            setState(() {
              _imageLocalPath = path;
            });
          } else {
            // Directory applicationDir = await getApplicationDocumentsDirectory();
            // // 判断路径是否存在
            // bool isDirExist = await Directory(applicationDir.path).exists();
            // if (!isDirExist) Directory(applicationDir.path).create();
            // // 直接保存，返回的就是保存后的文件
            // File saveFile = await File(applicationDir.path +
            //         "${DateTime.now().toIso8601String()}.jpg")
            //     .writeAsBytes(byteData.buffer.asUint8List());
            // setState(() {
            //   _imageLocalPath = saveFile.path;
            // });
          }
        }
      } else {
        if (await Permission.photos.request().isGranted) {
          print("22222");
          if (Platform.isAndroid) {
            final result = await ImageGallerySaver.saveImage(
                byteData.buffer.asUint8List());
            String res1 = result['filePath'];
            print(result);
            String path = res1.replaceAll("file://", '');
            setState(() {
              _imageLocalPath = path;
            });
          } else {
            print("3333333");
            String imagepath = await ImagePickers.saveByteDataImageToGallery(byteData.buffer.asUint8List());
            setState(() {
              _imageLocalPath = imagepath;
            });
           // String imagepath = await ImagePickers.
            // if (await Permission.storage.request().isGranted) {
            //   print("4444444");
            //   Directory applicationDir =
            //       await getApplicationDocumentsDirectory();
            //   // 判断路径是否存在
            //   bool isDirExist = await Directory(applicationDir.path).exists();
            //   if (!isDirExist) Directory(applicationDir.path).create();
            //   // 直接保存，返回的就是保存后的文件
            //  // String _imgpath = await 
            //   // File saveFile = await File(applicationDir.path +
            //   //         "${DateTime.now().toIso8601String()}.jpg")
            //   //     .writeAsBytes(byteData.buffer.asUint8List());
            //   // print(saveFile);
            //   // setState(() {
            //   //   _imageLocalPath = saveFile.path;
            //   // });
            // }
          }
        }
      }
      // BuildContext buildContext = _globalKey.currentContext;
      // if (null != buildContext) {
      //   RenderRepaintBoundary boundary = buildContext.findRenderObject();
      //   ui.Image image = await boundary.toImage();
      //   ByteData byteData =
      //       await image.toByteData(format: ui.ImageByteFormat.png);
      //   final result =
      //       await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      //   String res1 = result['filePath'];
      //   String path = res1.replaceAll("file://", '');
      //   setState(() {
      //     _imageLocalPath = path;
      //   });
      uploadsignpic();
    }
    //  RenderRepaintBoundary boundary =
    //     _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    // var image = await boundary.toImage(pixelRatio: 3.0);
    // ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
    // _postBytes = byteData?.buffer.asUint8List();
    // //保存到相册
    // var result = await ImageGallerySaver.saveImage(_postBytes!);
    // String path = result['filePath'].replaceAll("file://", '');
  }

  /// 截图，并且返回图片的缓存地址
  Future<String> _capturePng(File toFile) async {
    // 1. 获取 RenderRepaintBoundary
    RenderRepaintBoundary boundary =
        _globalKey.currentContext.findRenderObject();
    // 2. 生成 Image
    ui.Image image = await boundary.toImage();
    // 3. 生成 Uint8List
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    // 4. 本地存储Image
    // toFile.writeAsBytes(pngBytes);
    // return toFile.path;
    var result = await ImageGallerySaver.saveImage(pngBytes);
    //String path = result['filePath'].replaceAll("file://", '');
    String res1 = result['filePath'];
    String path = res1.replaceAll("file://", '');
    return path;
  }
}

class BoardPainter extends CustomPainter {
  BoardPainter(this.points);

  final List<Offset> points;

  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.red
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5.0;
    for (int i = 0; i < points.length - 1; i++) {
      if (points[i] != null && points[i + 1] != null) {
        canvas.drawLine(points[i], points[i + 1], paint);
      }
    }
  }

  bool shouldRepaint(BoardPainter other) => other.points != points;
}
